#include "Rational.h"

Rational::Rational(int x): x(x), y(1) {}

Rational::Rational(int x, int y): x(x), y(y) {}

Rational::Rational(Rational const & second): x(second.x), y(second.y) {}

Rational & Rational::operator+=(const Rational & second) {
	x = x*second.y + y*second.x;
	y *= second.y;	
	reduce();
	return *this;
}

Rational & Rational::operator-=(const Rational & second) {
	Rational tmp(second);
	operator +=(-tmp);
	return *this;
}

Rational & Rational::operator=(const Rational & second) {
	Rational tmp(second);
	swap(tmp);
	return *this;
}

Rational & Rational::operator*=(const Rational & second) {
	x *= second.x;
	y *= second.y;
	reduce();
	return *this;
}

Rational & Rational::operator/=(const Rational & second) {
	Rational tmp(second.y, second.x);
	operator *=(tmp);
	reduce();
	return *this;
}

void Rational::out() {
	std::cout << x << "/" << y << "\n";
}

Rational Rational::operator-() {
	return Rational(-x, y);
}


int Rational::reduce(void) {
	int a(x);
	int b(y);

	while(a!=0 && b!=0)
    {
       if(a >= b) {
		   a = a % b;
	   } else {
           b = b % a;
	   }
    }

	x /= a+b;
	y /= a+b;
	return a+b;
}

Rational::operator double() const {
	return (double) x / (double) y;
}

Rational & Rational::operator++() {
	operator+=(1);
	return *this;
}

Rational Rational::operator++(int) {
	Rational result = *this;
	++(*this);
	return result;
}

Rational & Rational::operator--() {
	operator-=(1);
	return *this;
}

Rational Rational::operator--(int) {
	Rational result = *this;
	--(*this);
	return result;
}

bool const operator<(const Rational &a, const Rational &b) {
	return a.x * b.y < b.x * a.y;
}

bool const operator==(const Rational &a, const Rational &b) {
	return !(a < b) && !(b < a);
}

bool const operator!=(const Rational &a, const Rational &b) {
	return !(a == b);
}

bool const operator>(const Rational &a, const Rational &b) {
	return b < a;
}

bool const operator<=(const Rational &a, const Rational &b) {
	return !(a > b);
}

bool const operator>=(const Rational &a, const Rational &b) {
	return !(a < b);
}

Rational operator+(const Rational &a, const Rational &b) {
	Rational tmp(a);
	return tmp += b;
}

Rational operator-(const Rational &a, const Rational &b) {
	Rational tmp(a);
	return tmp -= b;
}

Rational operator/(const Rational &a, const Rational &b) {
	Rational tmp(a);
	return tmp /= b;
}

Rational operator*(const Rational &a, const Rational &b) {
	Rational tmp(a);
	return tmp *= b;
}